package zx.x.modules.app.pw;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

/**
 * 来源于网络：http://blog.csdn.net/songdeitao/article/details/17304395
 * @author tot
 */
@Slf4j
public class JAXBXmlUtil {
    /**
     * 将对象直接转换成String类型的 XML输出
     *
     * @param obj
     * @return
     */
    public static String convertToXml(Object obj) {
        System.out.println("对象是什么："+ JSON.toJSONString(obj));
        // 创建输出流
        StringWriter sw = new StringWriter();
        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(obj.getClass());

            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                Boolean.TRUE);
            // 将对象转换成输出流形式的xml
            marshaller.marshal(obj, sw);
        } catch (JAXBException e) {
            log.error("convertToXml get some error==>",e);
        }
        return sw.toString();
    }

    public static String mapToXml(Map<String,Object> map) {
        // 创建输出流
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>\n");
        //值
        map.forEach((k,v)->{
            sb.append("<").append(k).append(">");
            sb.append(v.toString());
            sb.append("</").append(k).append(">\n");
        });
        sb.append("</xml>\n");
        return sb.toString();
    }

    @SuppressWarnings("unchecked")
    /**
     * 将String类型的xml转换成对象
     */
    public static <T> T convertToObj(String xmlStr,Class<T> clazz) {
        T xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = (T)unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            log.warn("convertToObj get some error==>",e);
        }
        return xmlObject;
    }



}
